package com.topmap.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Author: MaHuadong
 * @Date: 2019/7/17 12:58
 * @Version 1.0
 * 校验实现方法
 */

//变成spring的bean，在执行类扫描的时候可以扫描到它
@Component
public class ValidatorImpl implements InitializingBean {

    //通过javax定义的一套接口实现validator实现工具
    private Validator validator;


    //实现校验方法并返回校验结果
    public ValidationResult validator(Object bean){
        //实例化
        ValidationResult result=new ValidationResult();
        //调用方法
        Set<ConstraintViolation<Object>> constraintViolationSet =validator.validate(bean);
        if (constraintViolationSet.size()>0){
            //有错误
            result.setHasError(true);
            //java8特有的特性labmda表达式进行foreach循环
            constraintViolationSet.forEach(constraintViolation->{
                String errMsg=constraintViolation.getMessage();
                String propertyName=constraintViolation.getPropertyPath().toString();
                result.getErrorMsgMap().put(propertyName,errMsg);
            });
        }
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //将hibernate validator通过工厂的初始化方式使其实例化
        this.validator= Validation.buildDefaultValidatorFactory().getValidator();

    }
}
